<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\AppleTreesRecord;
use Carbon\Carbon;
use Brick\Math\RoundingMode;
use Illuminate\Database\Eloquent\Collection;

class AutoPlusAppleTree extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:auto-plus-tree';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
         AppleTreesRecord::query()
            ->whereNotNull('paid_at')
            ->where('expired_at','>',Carbon::now())
            ->chunk(50, function (Collection $records) {

             if ($records->isEmpty()) return false;

             foreach($records as $record){
                if($record->user->isNotValidVip()){
                  continue;
                }
                if($record->user->is_stop){
                  continue;
                }

                $ownRecordApples = big_decimal($record->appleTree->produce_apples)->dividedBy(30*86400 ,8 , RoundingMode::HALF_UP);
                $timeDist = time() - strtotime($record->updated_at);
                
                $addApples = $ownRecordApples->multipliedBy($timeDist);
                $dividend_money = $addApples;
                if($record->dividend_money){

                   $dividend_money = $addApples->plus($record->dividend_money);
                }
                
                $record->update(['dividend_money'=>$dividend_money]);
                account_apples($record->user)->plusGardenProduceApples($addApples);

             }

         });       
    }
}
